/**
	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package br.biofoco.p2p.services;

import java.util.Map;
import java.util.concurrent.Callable;

import com.google.common.collect.ImmutableMap;


public class ServiceTask implements Comparable<ServiceTask>, Callable<ServiceResult<?>> {
	
	private final long id;
	private long priority;
	private final Service<?> service;
	private final Map<String,String> params;
	
	public ServiceTask(long id, Service<?> service){
		this(id, service, ImmutableMap.<String,String>of());
	}
	
	public ServiceTask(long id, Service<?> service, Map<String, String> params){
		this.id = id;
		this.service = service;
		this.params  = params;
	}
	
	public long getID() {
		return id;
	}
	
	public void setPriority(long priority) {
		this.priority = priority;
	}

	public long getPriority() {
		return priority;
	}

	@Override
	public int compareTo(ServiceTask o) {
		if (priority == o.priority)
			return 0;
		
		return (priority > o.priority)? -1 : 1;
	}
	
	@Override
	public int hashCode() {
		return Long.valueOf(id).hashCode();
	}
	
	@Override
	public String toString() {
		return "id:" + id;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!(obj instanceof ServiceTask))
			return false;
		
		return id == ((ServiceTask) obj).id;
	}

	public ServiceResult<?> call() throws Exception {
		System.out.println("executing..." + this.toString());
		ServiceResult<?> result = service.execute(id, params);
		return result;
	}
}
